import React, { useState, useEffect } from "react";
import { AtActionSheet, AtInput, AtModal, AtModalContent } from "taro-ui";
import { View, Text, Button } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import api from "@api/api.js";
import _ from "lodash";

export default (props) => {
  const [sheetOpen, setSheetOpen] = useState(false); // sheet弹窗开关
  const [priceOpen, setPriceOpen] = useState(false); // 选择折扣弹窗开关
  const [payOpen, setPayOpen] = useState(false); // 选择支付方式弹窗开关
  const [hasExpertsDiag, setHasExpertsDiag] = useState(false); // 是否邀请了专家会诊
  const [simpleInfo, setSimpleInfo] = useState({}); // 价格总计
  const [countInfo, setCountInfo] = useState({}); // 价格计算
  const [param, setParam] = useState({});
  const [dtl, setDtl] = useState({}); // 价格详情
  const [sysParam, setSysParam] = useState({
    paymentTimesType: [],
    PaymentSchemes_discountRate: [],
  }); // 数据字典
  useEffect(() => {
    setSysParam(props.sysParam);
    if (props.current == 1) {
      setSimpleInfo(_.cloneDeep(props?.simpleInfo));
      setCountInfo(_.cloneDeep(props?.simpleInfo));
    }
    if (props.current == 2) {
      setHasExpertsDiag(props.hasExpertsDiag);
    }
  }, [props]);
  // 获取价格详情
  const getDetailsInfo = async () => {
    const { data } = await api.getDetailsInfo(props.id);
    setDtl(data);
    setParam({
      paymentTimesType: data.paymentTimesType,
      discountRate: data.discountRate,
      discountRateDesc: data.discountRateDesc,
      discountAmount: data.discountAmount,
      paymentItemList: data.paymentItemList,
    });
  };
  // 计算
  const price = (type, e) => {
    countInfo.afterDiscountAmount = (
      Number(simpleInfo.totalAmount) *
        Number(type == "discountRate" ? e : param.discountRate) *
        0.01 -
      Number(type == "discountAmount" ? e : param.discountAmount)
    ).toFixed(2);
    setCountInfo({ ...countInfo });
  };
  // 保存支付信息
  const savePayment = async () => {
    const { code } = await api.savePayment(param, props.id);
    if (code == 200) {
      closeSheet();
      props.getSimpleInfo(props.id);
    }
  };
  // 选择折扣
  const selectPrice = async (e) => {
    price("discountRate", e.paramCode);
    param.paymentItemList.map((item, index) => {
      inputSelect(index, item.paymentRate, {
        discountRate: e.paramCode,
        discountRateDesc: e.paramDesc,
      });
    });
    closePrice();
  };
  // 选择支付方式
  const selectPay = (e) => {
    setParam({
      ...param,
      paymentTimesType: e,
      paymentItemList: [
        {
          paymentAmount: countInfo.afterDiscountAmount,
          paymentOrder: 1,
          paymentRate: 100,
        },
      ],
    });
    closePay();
  };
  // 监听优惠金额改变
  const preferentialChange = (e) => {
    price("discountAmount", e);
    param.paymentItemList.map((item, index) => {
      inputSelect(index, item.paymentRate, { discountAmount: e });
    });
  };
  // 添加支付次数
  const addInput = (e) => {
    param.paymentItemList.push({
      paymentOrder: e,
      paymentAmount: 0,
      paymentRate: 0,
    });
    setParam({ ...param });
  };
  // 删除支付次数
  const deleteInput = (e) => {
    _.pull(param.paymentItemList, e);
    setParam({ ...param });
  };
  // 监听支付比例改变
  const inputSelect = (key, value, obj = {}) => {
    param.paymentItemList[key].paymentRate = value;
    param.paymentItemList[key].paymentAmount =
      Number(countInfo.afterDiscountAmount) * (Number(value) * 0.01);
    setParam({ ...param, paymentItemList: param.paymentItemList, ...obj });
  };
  // 打开下弹窗
  const openSheet = () => {
    setSheetOpen(true);
    getDetailsInfo();
  };
  // 关闭下弹窗
  const closeSheet = () => {
    setCountInfo(simpleInfo);
    setSheetOpen(false);
    getDetailsInfo();
  };
  // 打开折扣弹窗
  const openPrice = () => {
    setPriceOpen(true);
  };
  // 关闭折扣弹窗
  const closePrice = () => {
    setPriceOpen(false);
  };
  // 打开支付方式弹窗
  const openPay = () => {
    setPayOpen(true);
  };
  // 关闭支付方式弹窗
  const closePay = () => {
    setPayOpen(false);
  };
  // 跳转专家列表
  const goExpertList = () => {
    Taro.navigateTo({
      url: `/pages/expertList/index?id=${props.id}`,
    });
  };
  // 跳转添加日程
  const addEvent = () => {
    Taro.reLaunch({
      url: `/pages/schedule/index?diagnosisSchemesId=${props.id}`,
    });
  };
  return (
    <>
      {props.type != "expert" ? (
        <View className="footer">
          {props.current == 1 && props.clinicSchemesId && (
            <>
              <View className="dtFooter borderBottom">
                <View className="at-row at-row__align--center">
                  <View className="at-col">
                    <View className="total">
                      总计
                      <View className="totalNum">
                        ¥{simpleInfo.afterDiscountAmount}
                      </View>
                    </View>
                    <View className="payWay">
                      {simpleInfo.paymentTimesDesc}
                    </View>
                  </View>
                  <View className="dtlBtn payWay at-col" onClick={openSheet}>
                    查看详情
                  </View>
                </View>
              </View>
              {/* 价格详情弹窗 */
              sheetOpen && (
                <AtActionSheet isOpened={sheetOpen}>
                  <View className="sheet">
                    <View className="sheetTitle font" onClick={closeSheet}>
                      收起<View className="iconfont icon-xiangxia"></View>
                    </View>
                    <View className="sheetCont borderBottom">
                      <View className="fontbold">价格小计</View>
                      {dtl.clinicSimpleInfoList &&
                        dtl.clinicSimpleInfoList.map((item) => {
                          return (
                            <View>
                              <View className="sheetName font">
                                {item.clinicName}
                              </View>
                              <View className="sheetTooth font">
                                {item.toothPosition.map((items) => {
                                  return items + "/";
                                })}
                                <View className="sheetNum font">
                                  ￥{item.totalAmount}
                                </View>
                              </View>
                            </View>
                          );
                        })}
                    </View>
                    <View className="sheetCont borderBottom">
                      <View className="fontbold">折扣和优惠</View>
                      <View className="discount at-row">
                        <View className="at-col-6">
                          <View
                            className="discountSelect font"
                            onClick={openPrice}
                          >
                            <View>
                              {param.discountRate
                                ? param.discountRateDesc
                                : "请选择折扣"}
                            </View>
                            <View className="iconfont icon-xiangxia"></View>
                          </View>
                        </View>
                        <View className="at-col-6">
                          <View className="preferential">
                            <AtInput
                              placeholderClass="font"
                              placeholder="请输入优惠金额"
                              value={param.discountAmount}
                              onChange={preferentialChange.bind(this)}
                            />
                            <View className="preferentialIcon">￥</View>
                          </View>
                        </View>
                      </View>
                    </View>
                    <View className="sheetCont">
                      <View className="fontbold">
                        支付方式
                        <View className="fontBlue" onClick={openPay}>
                          切换支付方式
                        </View>
                      </View>
                      <View className="payment">
                        {param.paymentItemList &&
                          param.paymentItemList.map((item, index) => {
                            return (
                              <View className="at-row">
                                <View className="at-col">
                                  <View className="payMentOne">
                                    <View className="oneOrder">
                                      第{item.paymentOrder}次支付
                                    </View>
                                    <View className="oneNum">
                                      ￥{item.paymentAmount.toFixed(2)}
                                    </View>
                                    <View className="oneType">
                                      <AtInput
                                        name={"paymentRate" + index}
                                        value={item.paymentRate}
                                        placeholder="百分比"
                                        onChange={inputSelect.bind(this, index)}
                                      />
                                      <Text> %</Text>
                                    </View>
                                  </View>
                                </View>
                                {param.paymentTimesType ==
                                "paymentTimesType_single" ? (
                                  ""
                                ) : (
                                  <View
                                    className="at-col at-col-1 at-col--auto"
                                    onClick={() => {
                                      deleteInput(item);
                                    }}
                                  >
                                    <View className="iconfont icon-shanchu"></View>
                                  </View>
                                )}
                              </View>
                            );
                          })}
                        {param.paymentTimesType == "paymentTimesType_single" ? (
                          ""
                        ) : (
                          <View
                            className="add fontBlue"
                            onClick={() => {
                              addInput(param.paymentItemList.length + 1);
                            }}
                          >
                            添加
                          </View>
                        )}
                      </View>
                    </View>
                    <View className="footer">
                      <View className="dtFooter">
                        <View className="total">
                          小计
                          <View className="totalNum">
                            ¥{countInfo.afterDiscountAmount}
                          </View>
                        </View>
                        <View className="payWay">
                          {countInfo.paymentTimesDesc},已优惠
                          {(
                            simpleInfo.totalAmount -
                            countInfo.afterDiscountAmount
                          ).toFixed(2)}
                          元
                        </View>
                      </View>
                      <View className="saveFooter at-row">
                        <View className="at-col">
                          <View className="clearBtn" onClick={closeSheet}>
                            取消
                          </View>
                        </View>
                        <View className="at-col">
                          <View className="saveBtn" onClick={savePayment}>
                            确认
                          </View>
                        </View>
                      </View>
                    </View>
                  </View>
                  {/* 折扣弹窗 */
                  priceOpen && (
                    <AtModal isOpened={priceOpen}>
                      <AtModalContent>
                        <View className="sheetModal">
                          <View className="modalTitle">
                            选择折扣
                            <View
                              className="iconfont icon-guanbi"
                              onClick={closePrice}
                            ></View>
                          </View>
                          <View className="modalList">
                            {sysParam.PaymentSchemes_discountRate.map(
                              (item) => {
                                return (
                                  <View
                                    className={
                                      param.discountRate == item.paramCode
                                        ? "modalItem active"
                                        : "modalItem"
                                    }
                                    onClick={() => {
                                      selectPrice(item);
                                    }}
                                  >
                                    {item.paramDesc}
                                    {param.discountRate == item.paramCode ? (
                                      <View className="iconfont icon-dui"></View>
                                    ) : (
                                      ""
                                    )}
                                  </View>
                                );
                              }
                            )}
                          </View>
                        </View>
                      </AtModalContent>
                    </AtModal>
                  )}
                  {/* 支付方式弹窗 */
                  payOpen && (
                    <AtModal isOpened={payOpen}>
                      <AtModalContent>
                        <View className="sheetModal">
                          <View className="modalTitle">
                            切换支付方式
                            <View
                              className="iconfont icon-guanbi"
                              onClick={closePay}
                            ></View>
                          </View>
                          <View className="modalList">
                            {sysParam.paymentTimesType.map((item) => {
                              return (
                                <View
                                  className={
                                    param.paymentTimesType == item.paramCode
                                      ? "modalItem active"
                                      : "modalItem"
                                  }
                                  onClick={() => {
                                    selectPay(item.paramCode);
                                  }}
                                >
                                  {item.paramDesc}
                                  {param.paymentTimesType == item.paramCode ? (
                                    <View className="iconfont icon-dui"></View>
                                  ) : (
                                    ""
                                  )}
                                </View>
                              );
                            })}
                          </View>
                        </View>
                      </AtModalContent>
                    </AtModal>
                  )}
                </AtActionSheet>
              )}
            </>
          )}
          {props.current == 2 && !hasExpertsDiag && (
            <View className="dtFooter borderBottom">
              <View className="btn" onClick={goExpertList}>
                邀请专家会诊
              </View>
            </View>
          )}
          <View className="saveFooter myButton at-row">
            <View className="font at-col" onClick={addEvent}>
              添加日程
            </View>
            <Button
              className="font at-col"
              openType="share"
              data-type="patient"
            >
              分享给患者
            </Button>
            <View className="at-col">
              <View className="saveBtn" onClick={props.onchange}>
                保存方案
              </View>
            </View>
          </View>
        </View>
      ) : (
        props.current == 1 && (
          <View className="bottomBtn">
            <View onClick={props.onchange}>提交</View>
          </View>
        )
      )}
    </>
  );
};
